package com.huawei.csi.tool.controller;

import com.google.gson.reflect.TypeToken;
import com.huawei.csi.tool.config.GlobalConfig;
import com.huawei.csi.tool.domain.Score;
import com.huawei.csi.tool.log.JavaFXAppender;
import com.huawei.csi.tool.util.FileUtil;
import com.huawei.csi.tool.validation.AbstractVerify;
import com.huawei.csi.tool.validation.VerifyManager;
import com.leewyatt.rxcontrols.controls.RXTextField;
import com.leewyatt.rxcontrols.event.RXActionEvent;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.DirectoryChooser;
import org.controlsfx.control.MaskerPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;

public class AnalysisDataPageController implements Initializable {
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisDataPageController.class);
    /**
     * 上次打开的文件路径
     */
    private static String LAST_DIRECTORY = "";
    /**
     * 需要扫描的文件名称
     */
    private List<String> scanFiles;
    @FXML
    private RXTextField choseFilePath;
    @FXML
    private TextArea logTextArea;
    @FXML
    private MaskerPane maskerPane;
    @FXML
    private Button startScan;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        JavaFXAppender fxAppender = new JavaFXAppender(this.logTextArea);
        ch.qos.logback.classic.Logger loggerRoot = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
        loggerRoot.addAppender(fxAppender);
        // 配置Appender，例如设置名称和过滤器
        fxAppender.setName("javaFx");
        fxAppender.start();
        Optional<Object> optionalObject = FileUtil.jsonFile2Class("json/file.json", new TypeToken<List<String>>() {
        }.getType());
        optionalObject.ifPresent(o -> scanFiles = (List<String>) o);
    }

    @FXML
    void onChoseFilePathAction(RXActionEvent event) {
        // 恢复上一次选择的目录
        File initialDirectory = new File(LAST_DIRECTORY);
        if (!initialDirectory.exists() || !initialDirectory.isDirectory()) {
            initialDirectory = null;
        }
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("请选择文件");
        if (initialDirectory != null) {
            directoryChooser.setInitialDirectory(initialDirectory);
        }
        File selectedDirectory = directoryChooser.showDialog(GlobalConfig.rootStage);
        if (selectedDirectory != null) {
            String absolutePath = selectedDirectory.getAbsolutePath();
            if (!absolutePath.isEmpty()) {
                LAST_DIRECTORY = absolutePath;
                choseFilePath.setText(absolutePath);
            }
        }
    }

    @FXML
    void onStartScanAction(ActionEvent event) {
        LOGGER.info("Start scan ...");
        String filePathText = choseFilePath.getText();
        if (filePathText == null || filePathText.isEmpty()) {
            LOGGER.info("请选择文件！");
            alert("请选择文件！");
            return;
        }
        Path path = Paths.get(filePathText);
        if (!Files.exists(path) && !Files.isDirectory(path)) {
            LOGGER.info("文件目录不存在！");
            alert("文件目录不存在！");
            return;
        }
        Map<String, Path> sccanMap = FileUtil.findRootDirectoryRegularFile(path, scanFiles);
        if (sccanMap.isEmpty()) {
            LOGGER.info("文件目录中，需验证的文件不存在！");
            alert("文件目录中，需验证的文件不存在！");
            return;
        }
        Score score = Score.getInstance();
        sccanMap.forEach((name, pathFile) -> {
            if (Files.isRegularFile(pathFile)) { // 只读取根目录下的文件数据
                String[] split = name.split("\\.");
                String verifyName = split[0].toUpperCase();
                AbstractVerify abstractVerify = VerifyManager.VALIDA_MAP.get(verifyName);
                boolean validate = abstractVerify.isVerifiedPassed(pathFile);
                score.initScore(verifyName, validate);
            }
        });
        LOGGER.info("End scan ...");
    }

    private void alert(String text) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.initOwner(GlobalConfig.rootStage);
        alert.setTitle(Alert.AlertType.WARNING.name());
        alert.setHeaderText(text);
        alert.showAndWait();
    }

}
